import 'dart:async';
import 'dart:convert';

import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/common/common.dart';
import 'package:appflutterhomeschool/model/student_information_model.dart';
import 'package:appflutterhomeschool/res/styles.dart';
import 'package:appflutterhomeschool/route/application.dart';
import 'package:appflutterhomeschool/route/routes.dart';
import 'package:appflutterhomeschool/ui/dialogs/prompt_dialog_widgets.dart';
import 'package:appflutterhomeschool/utils/sp_util.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';

///用户：Nine Tailed Fox
///时间：2020/6/10
///邮箱：1037438704@qq.com
///功能：注册状态管理
class RegisterViewModel extends ChangeNotifier {
  DioUtils dioUtils = DioUtils.getInstance();

  //是否显示密码
  bool obscureText = true;
  TapGestureRecognizer recognizer1 = TapGestureRecognizer();
  bool consentAgreement = true;

  //手机号码
  String buttonName;
  String titleTar;

  //密码
  TextEditingController passwordTextEditing = TextEditingController();
  TextEditingController phoneTextEditing = TextEditingController();

  //验证码
  TextEditingController vCodeTextEditing = TextEditingController();

  int pageTag;

  //用于保存当前倒计时
  int _countDown = 59;
  Timer _countdownTimer;
  String codeCountdownStr = "获取验证码";
  Color resendColor = Colors.blue;

  Widget textVisition() {
    return Visibility(
      visible: pageTag == 3,
      child: Container(
        margin: EdgeInsets.only(top: ScreenUtil().setWidth(43)),
        child: Text.rich(TextSpan(children: [
          TextSpan(text: "当前登录账号为", style: TextStyles.textGray31),
          TextSpan(text: Constant.getPhone(), style: TextStyles.textDark31),
          TextSpan(text: "，修改后，将使用新手机号登录", style: TextStyles.textGray31),
        ])),
      ),
    );
  }

  BuildContext me;

  RegisterViewModel(this.me, this.pageTag);

  initView() {
    switch (pageTag) {
      case 0:
        titleTar = "注册";
        buttonName = "立即注册";
        break;
      case 1:
        titleTar = "忘记密码";
        buttonName = "找回密码";
        break;
      case 2:
        titleTar = "绑定手机号";
        buttonName = "绑定";
        break;
      case 3:
        titleTar = "修改绑定手机号";
        buttonName = "确定";
        break;
    }
    recognizer1.onTap = () {
      Application().navigatePushToPage(me, Routes.agreedAnnouncementPage, {});
    };
  }

  //点击事件
  initEvent(int tag) {
    switch (tag) {
      case 0:
        //密码显示隐藏
        obscureText = !obscureText;
        notifyListeners();
        break;
      case 1:
        //协议按钮
        consentAgreement = !consentAgreement;
        notifyListeners();
        break;
    }
  }

  sureOnTap() async {
    switch (pageTag) {
      case 0:
//        buttonName = "立即注册";
        //需要 手机号  验证码  密码
        if (passwordTextEditing.text == null ||
            phoneTextEditing.text.length != 11) {
          Fluttertoast.showToast(msg: "请输入正确手机号");
          return;
        }
        if (passwordTextEditing.text.length < 6) {
          Fluttertoast.showToast(msg: "请输入密码");
          return;
        }
        if (vCodeTextEditing.text.length < 6) {
          Fluttertoast.showToast(msg: "请输入验证码");
          return;
        }
        PromptDialogWidgets(me).showLoadingDialog((Function function) async {
          await dioUtils.post(ApiService.phoneRegister, {
            "phone": phoneTextEditing.text ?? "",
            "password": passwordTextEditing.text ?? "",
            "verification_code": vCodeTextEditing.text ?? "",
          }, (successCallBack) {
            Fluttertoast.showToast(msg: successCallBack["message"]);
            Navigator.pop(me);
            function();
          }, (errorCallBack) {
            function();
          });
        });

        break;
      case 1:
        PromptDialogWidgets(me).showLoadingDialog((Function function) async {
          await dioUtils.post(ApiService.updatePassword, {
            "phone": phoneTextEditing.text ?? "",
            "password": passwordTextEditing.text ?? "",
            "verification_code": vCodeTextEditing.text ?? "",
          }, (successCallBack) {
            Fluttertoast.showToast(msg: successCallBack["message"]);
            Navigator.pop(me);
            function();
          }, (errorCallBack) {
            function();
          });
        });
        break;
      case 2:
//        buttonName = "绑定";

        PromptDialogWidgets(me).showLoadingDialog((Function function) async {
          await dioUtils.post(ApiService.oauthRegister, {
            "phone": phoneTextEditing.text ?? "",
            "verification_code": vCodeTextEditing.text ?? "",
            "password": passwordTextEditing.text ?? "",
            "openid": Constant.code,
          }, (successCallBack) {
            SpUtil.putString("phone", phoneTextEditing.text);
            SpUtil.putString("password", passwordTextEditing.text);
            Fluttertoast.showToast(msg: successCallBack["message"]);
            function();
            xinxiSure(successCallBack);
          }, (errorCallBack) {
            function();
          });
        });
        break;
      case 3:
        PromptDialogWidgets(me).showLoadingDialog((Function function) async {
          await dioUtils.post(ApiService.updatePhone, {
            "phone": phoneTextEditing.text ?? "",
            "verification_code": vCodeTextEditing.text ?? "",
            "token": Constant.getToken(),
          }, (successCallBack) {
            SpUtil.putString("phone", phoneTextEditing.text);
            Fluttertoast.showToast(msg: successCallBack["message"]);
            Navigator.pop(me);
            function();
          }, (errorCallBack) {
            function();
          });
        });
//        buttonName = "确定";
        break;
    }
  }

  reGetCountdown() {
    if (_countdownTimer != null) {
      return;
    }
    if (phoneTextEditing.text == null || phoneTextEditing.text.length < 11) {
      Fluttertoast.showToast(msg: "请输入手机号");
      return;
    }
    //获取验证码
    erificationCode();
    // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
    codeCountdownStr = '${_countDown--}后重新获取';
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      if (_countDown > 0) {
        resendColor = Colors.grey;
        codeCountdownStr = '${_countDown--}后重新获取';
      } else {
        resendColor = Colors.blue;
        codeCountdownStr = '获取验证码';
        _countDown = 59;
        _countdownTimer.cancel();
        _countdownTimer = null;
      }
      notifyListeners();
    });
  }

  // 不要忘记在这里释放掉Timer
  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  //获取验证码
  void erificationCode() {
    //需要手机号
    DioUtils.getInstance().post(ApiService.verificationCode, {
      "phone": phoneTextEditing.text,
    }, (successCallBack) {
      Fluttertoast.showToast(msg: successCallBack["message"]);
    }, (errorCallBack) {
      print("errorCallBack ======== $errorCallBack");
    });
  }


  xinxiSure(Map successCallBack) {
    SpUtil.putString("role_now", successCallBack["data"]["role_now"] ?? "");
    SpUtil.putString("token", successCallBack["data"]["token"] ?? "");
    DioUtils.getInstance(tag: 1);
    Dio2Utils.getInstance(tag: 1);
    Fluttertoast.showToast(msg: successCallBack["message"]);
    Navigator.pop(me);
    if (successCallBack["data"]["role_now"] == null ||
        successCallBack["data"]["role_now"] == "") {
      Application()
          .navigatePushToPage(me, Routes.switchIdentityPage, {"pageTag": 0});
    } else {
      StudentInformationModel studentInformationModel;
      if (successCallBack["data"]["role_now"] == "TEACHER") {
        if (successCallBack["data"]['student_now'] != null &&
            successCallBack["data"]['student_now'].toString().isNotEmpty) {
          studentInformationModel = StudentInformationModel.fromJsonLogin(
              successCallBack["data"]['student_now']);
        }
        studentInformationModel = StudentInformationModel.fromJsonLogin(
            successCallBack["data"]['cls_now']);
      } else {
        if (successCallBack["data"]['student_now'] != null &&
            successCallBack["data"]['student_now'].toString().isNotEmpty) {
          studentInformationModel = StudentInformationModel.fromJsonLogin(
              successCallBack["data"]['student_now']);
        }
      }
      if (studentInformationModel != null) {
        SpUtil.putString(
            "getStudent", jsonEncode(studentInformationModel.toJson()));
      }
      Application().navigatePushToPage(me, Routes.mainTabPage, {});
    }
  }
}
